﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ResxHelper.Logic.Actions;
using ResxHelper.Logic.Readers;
using ResxHelper.Object;

namespace ResxHelper.Logic.Converter
{
    public class ConvertBulkAndroid : BulkConverterBase
    {
        private const string ResourceTopLevelDirectory = "res";
        public ConvertBulkAndroid()
        {
            SaveFileType = SaveFileType.AndroidResource;
        }

        #region -- Resource To Excel --

        public override void ToExcel(string inputPath, string outputPath)
        {
            // create temp directory
            WorkingDirectory = ExtractZipToTempDirectory(inputPath);

            // read all of the resource files
            var resourceFiles = ReadDirectories(WorkingDirectory.FullName, ResourceTopLevelDirectory);

            // convert each file to an excel file
            var paths = SaveTempExcelFiles(WorkingDirectory.FullName, resourceFiles);

            // create a new zip
            var zipRequest = new SaveZipRequest(paths, outputPath, true);
            SaveActionInvoker.Save(zipRequest, SaveFileType.Zip, outputPath);

            // delete the temp directory
            Directory.Delete(WorkingDirectory.FullName, true);
        }

        protected override string GetExportFileName(ResourceFile file)
        {
            // remove the temp directory to give us the file structure
            var actualPath = file.FilePath.Replace(string.Format("{0}\\", WorkingDirectory.FullName), string.Empty);
            var fileName = Path.GetFileNameWithoutExtension(file.FilePath);
            var pathOnly = Path.GetDirectoryName(actualPath);

            var pathSplit = pathOnly.Split('\\').ToList();

            var directoryString = string.Join("#", pathSplit);

            var culture = string.IsNullOrEmpty(file.CultureInfo.Name) ? "en" : file.CultureInfo.Name;
            var saveFileName = string.Format("{0}#{1}.{2}.xls", directoryString, fileName, culture);

            return saveFileName;
        }

        protected override IEnumerable<ResourceFile> ReadDirectoryFiles(string path)
        {
            var resourceFiles = new List<ResourceFile>();

            // go find all of the values directories
            foreach (var valuesDirectory in Directory.GetDirectories(path)
                                                  .Where(d => d.Contains("values")))
            {
                // read each file for each directory
                foreach (var resourceFile in Directory.GetFiles(valuesDirectory)
                                                      .Where(f => Path.GetExtension(f) == ".xml"))
                {
                    var reader = ResourceFileReaderFactory.GetReader(resourceFile, ResourceType.Android);
                    try
                    {
                        var resourceFileObj = reader.Read();
                        resourceFiles.Add(resourceFileObj);
                    }
                    catch(Exception ex)
                    {
                        // file probably wasn't a resource file
                        // TODO: log?
                    }
                }
            }

            return resourceFiles;
        }

        #endregion

        #region -- Excel To Resource --

        public override void ToResource(string inputPath, string outputPath)
        {
            // extract zip to temp directory
            var tempDirectory = ExtractZipToTempDirectory(inputPath);

            // read all files to resource files
            var resourceFiles = ReadExcelFiles(tempDirectory.FullName);

            // make converstion and create structure
            var savedDirectory = SaveToStructure(tempDirectory.FullName, resourceFiles);

            // save zip
            SaveZipDirectory(outputPath, savedDirectory);

            // cleanup
            Directory.Delete(tempDirectory.FullName, true);
        }

        protected override string GetFilePathFromFileName(string fileName)
        {
            var pathSplit = fileName.Split('#');
            var importedFileName = pathSplit.Last();
            pathSplit = pathSplit.Take(pathSplit.Length - 1).ToArray();

            var fileSplit = importedFileName.Split('.');
            var actualFileName = fileSplit[0];
            var culture = fileSplit[1];

            // rename directory for culture if applicable
            for (var i = 0; i < pathSplit.Length; i++)
            {
                if (pathSplit[i] == "values" && culture.ToLower() != "en")
                {
                    pathSplit[i] = string.Format("{0}-{1}", pathSplit[i], culture);
                }
            }

            var directoryPathString = string.Join("\\", pathSplit);

            var filePath = string.Format("{0}\\{1}.xml", directoryPathString, actualFileName);

            return filePath;
        }

        #endregion
    }
}
